package com.m31skytech.dungeonstool.blockentitys;

import com.m31skytech.dungeonstool.BlockEntityRegistry;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;

import javax.annotation.Nullable;

public class TeleportPointBlockEntity extends BlockEntity {
    private BlockPos bindPos;
    private ResourceKey<Level> bindDimension; // 存储绑定维度


    public TeleportPointBlockEntity(BlockPos pos, BlockState state) {
        super(BlockEntityRegistry.TELEPORT_POINT_BLOCK_ENTITY.get(), pos, state);
    }

    @Override
    public void load(@NotNull CompoundTag tag) {
        super.load(tag);
        if (tag.contains("bindPos")) {
            bindPos = BlockPos.of(tag.getLong("bindPos"));
        }
        if (tag.contains("bindDimension")) {
            bindDimension = ResourceKey.create(Registry.DIMENSION_REGISTRY
                    , new ResourceLocation(tag.getString("bindDimension")));
        }
    }

    @Override
    protected void saveAdditional(@NotNull CompoundTag tag) {
        super.saveAdditional(tag);
        if (bindPos != null) {
            tag.putLong("bindPos", bindPos.asLong());
        }
        if (bindDimension != null) {
            tag.putString("bindDimension", bindDimension.location().toString());
        }
    }

    @Nullable
    @Override
    public ClientboundBlockEntityDataPacket getUpdatePacket() {
        return ClientboundBlockEntityDataPacket.create(this);
    }

    public BlockPos getBindPos() {
        return bindPos;
    }
    public ResourceKey<Level> getBindDimension(){
        return bindDimension;
    }


    public void setBindPos(BlockPos bindPos,Level level) {
        this.bindPos = bindPos;
        if (null!= level)this.bindDimension = level.dimension(); // 设置绑定维度
        setChanged();
    }
    public boolean isBound(){
        return null!= bindPos;
    }
}